package com.ruoyi.web.controller.app;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.app.domain.AppImGroup;
import com.ruoyi.app.domain.AppImGroupJoinLog;
import com.ruoyi.app.domain.AppUser;
import com.ruoyi.app.domain.bo.AppImGroupBo;
import com.ruoyi.app.domain.vo.AppUserVo;
import com.ruoyi.app.mapper.AppImGroupJoinLogMapper;
import com.ruoyi.app.service.IAppImGroupService;
import com.ruoyi.app.service.IAppUserService;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.im.core.TxTemplate;
import com.ruoyi.im.model.CreateGroupReq;
import com.ruoyi.system.domain.UpAppImGroupReq;
import com.ruoyi.web.req.GroupReq;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;

/**
 * 群组
 *
 * @author ruoyi
 * @date 2025-11-11
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/imGroup")
public class AppImGroupController extends BaseController {

    private final IAppImGroupService iAppImGroupService;

    @Autowired
    private TxTemplate txTemplate;

    private final IAppUserService appUserService;

    private final AppImGroupJoinLogMapper appImGroupJoinLogMapper;




    /**
     * 创建群聊
     * @param bo
     * @return
     */
    @PostMapping("createGroup")
    public R<Object> createGroup(@RequestBody CreateGroupReq bo) {
        Long ownUserId = LoginHelper.getUserId();
        bo.getMeberList().add(ownUserId.toString());
        if (CollUtil.isEmpty(bo.getMeberList())){
            return R.fail("请选择群成员");
        }
        String groupName = "";
        int index = 1;
        for (String userId : bo.getMeberList()) {
            AppUserVo appUserVo = appUserService.queryById(Long.valueOf(userId));
            groupName = groupName + appUserVo.getNickName() + ",";
            index ++;
            if (index > 3){
                break;
            }
        }
        String groupImage = "http://106.53.181.247:9777/profile/upload/2025/08/18/edfa38f9-37c7-401d-946e-0fe17914398b.png";
        String group = txTemplate.createGroup(groupName, ownUserId.toString(), bo.getNotification(), bo.getMeberList(), groupImage);
        //记录到数据库
        AppImGroupBo appImGroupBo = new AppImGroupBo();
        appImGroupBo.setId(group);
        appImGroupBo.setGroupName(groupName);
        appImGroupBo.setGroupAvatar(groupImage);
        appImGroupBo.setOwnerId(bo.getUserId());
        appImGroupBo.setGroupType(1L);
        appImGroupBo.setRemark("");
        appImGroupBo.setStatus(1L);
        appImGroupBo.setMember(bo.getMeberList().toString());
        iAppImGroupService.insertByBo(appImGroupBo);

        //记录进群记录
        AppUserVo appUserVo = appUserService.queryById(ownUserId);
        List<AppUserVo> appUserVos = appUserService.selectList(new LambdaQueryWrapper<AppUser>().in(AppUser::getId, bo.getMeberList()));
        Map<Long, AppUserVo> userVoMap = appUserVos.stream().collect(Collectors.toMap(AppUserVo::getId, appUserVo1 -> appUserVo1));
        List<String> meberList = bo.getMeberList();
        for (String userId : meberList) {
            AppImGroupJoinLog appImGroupJoinLog = new AppImGroupJoinLog();
            appImGroupJoinLog.setGroupId(group);
            appImGroupJoinLog.setUserId(Long.valueOf(userId));
            appImGroupJoinLog.setNickname(userVoMap.get(Long.valueOf(userId)).getNickName());
            appImGroupJoinLog.setAvatar(userVoMap.get(Long.valueOf(userId)).getAvatar());
            appImGroupJoinLog.setActionType(1L);
            appImGroupJoinLog.setSourceUserId(appUserVo.getId());
            appImGroupJoinLog.setSourceNickname(appUserVo.getNickName());
            appImGroupJoinLogMapper.insert(appImGroupJoinLog);
        }


        return R.ok(appImGroupBo);
    }


    /**
     * 搜索群聊
     * @return
     */
    @PostMapping("searchGroup")
    public R<List<AppImGroup>> searchGroup(@Param("keyWord") String keyWord) {
        return R.ok(iAppImGroupService.searchGroup(keyWord));
    }

    /**
     * 设置群搜索开关
     * 0 可以搜到 1不能搜到
     * @return
     */
    @PostMapping("setSearchGroupFlag")
    public R<?> setSearchGroupFlag(@Param("groupId") String groupId,
                                   @Param("flag") Integer flag) {
        return R.ok(iAppImGroupService.setSearchGroupFlag(groupId,flag));
    }


    /**
     * 根据id查询群聊信息
     * @return
     */
    @PostMapping("selGroupById")
    public R<?> selGroupById(@Param("groupId") String groupId) {
        return R.ok("查询成功",iAppImGroupService.selGroupById(groupId));
    }


    /**
     * 修改群信息
     * @return
     */
    @PostMapping("updateGroupData")
    public R<?> updateGroupData(UpAppImGroupReq req) {
        return R.ok("修改成功",iAppImGroupService.updateGroupData(req));
    }


    /**
     * 邀人进群
     * @return
     */
    @PostMapping("addGroupMember")
    public R<?> addGroupMember(@RequestBody GroupReq groupReq) {
        return R.ok("添加成功",iAppImGroupService.addGroupMember(groupReq.getGroupId(),groupReq.getUserIdList()));
    }

    /**
     * 移除群成员
     * @return
     */
    @PostMapping("removeGroupMember")
    public R<?> removeGroupMember(@RequestBody GroupReq groupReq) {
        return R.ok("移除成功",iAppImGroupService.removeGroupMember(groupReq.getGroupId(),groupReq.getUserIdList()));
    }



    /**
     * 全体禁言
     * @return
     */
    @PostMapping("silenceAllGroupMember")
    public R<?> silenceAllGroupMember(@Param("groupId") String groupId) {
        return R.ok("禁言成功",iAppImGroupService.silenceAllGroupMember(groupId));
    }

    /**
     * 解除全体禁言
     * @return
     */
    @PostMapping("cancelSilenceAllGroupMember")
    public R<?> cancelSilenceAllGroupMember(@Param("groupId") String groupId) {
        return R.ok("解除禁言成功",iAppImGroupService.cancelSilenceAllGroupMember(groupId));
    }




    /**
     * 禁言列表
     * @return
     */
    @PostMapping("silenceGroupList")
    public R<?> silenceGroupList(@Param("groupId") String groupId) {
        return R.ok("成功",iAppImGroupService.silenceGroupList(groupId));
    }


    /**
     * 禁言群成员
     * @return
     */
    @PostMapping("silenceGroupMember")
    public R<?> silenceGroupMember(@RequestBody GroupReq groupReq) {
        return R.ok("禁言成功",iAppImGroupService.silenceGroupMember(groupReq.getGroupId(),groupReq.getUserIdList()));
    }


    /**
     * 移除禁言群成员
     * @return
     */
    @PostMapping("removeSilenceGroupMember")
    public R<?> removeSilenceGroupMember(@RequestBody GroupReq groupReq) {
        return R.ok("移除禁言成功",iAppImGroupService.removeSilenceGroupMember(groupReq.getGroupId(),groupReq.getUserIdList()));
    }


    /**
     * 解散群聊
     * @return
     */
    @PostMapping("delGroup")
    public R<?> delGroup(@Param("groupId") String groupId) {
        return R.ok("解散成功",iAppImGroupService.delGroup(groupId));
    }

    /**
     * 查询共同群聊
     * @return
     */
    @PostMapping("selTongGroup")
    public R<?> selTongGroup(@Param("userId") Long userId,
                             @Param("targetId") Long targetId) {
        return R.ok("查询成功",iAppImGroupService.selTongGroup(userId,targetId));
    }


    /**
     * 添加管理员
     * @return
     */
    @PostMapping("addGroupManager")
    public R<?> addGroupManager(@RequestBody GroupReq groupReq) {
        return R.ok("添加成功",iAppImGroupService.addGroupManager(groupReq.getGroupId(),groupReq.getUserIdList()));
    }


    /**
     * 取消群管理员
     * @return
     */
    @PostMapping("cancelGroupManager")
    public R<?> cancelGroupManager(@RequestBody GroupReq groupReq) {
        return R.ok("取消成功",iAppImGroupService.cancelGroupManager(groupReq.getGroupId(),groupReq.getUserIdList()));
    }


    /**
     * 获取群管理员数据
     * @return
     */
    @PostMapping("getGroupManagerData")
    public R<?> getGroupManagerData(@Param("groupId") String groupId) {
        return R.ok("查询成功",iAppImGroupService.getGroupManagerData(groupId));
    }


    /**
     * 忽略群验证信息
     * @return
     */
    @PostMapping("ignoreGroupApply")
    public R<?> ignoreGroupApply(@RequestBody List<Long> ids) {
        return R.ok("操作成功",iAppImGroupService.ignoreGroupApply(ids));
    }

}
